import { type ReactNode } from 'react';
import { authMiddleware } from '@/lib/api';
import { cookies } from 'next/headers';
import { queryPath, queryPostNewInfo } from '@/services/api';
import type { IPath, IPostNewInfo } from '@/interfaces';
import EditNav from '@/app/[locale]/posts/[id]/edit/nav/edit-nav';
import Wrapper from '@/app/[locale]/posts/[id]/edit/wrapper';

async function getData() {
  try {
    const token = authMiddleware(cookies());
    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/',
      },
    });
    const req2 = queryPostNewInfo({
      baseURL: process.env.APP_API_SERVER,
      token,
    });

    const responses = await Promise.all([req1, req2]);
    const resp1 = await ((await responses[0]) as Response).json();
    const resp2 = await ((await responses[1]) as Response).json();

    return {
      isSuccess: true,
      path: resp1.data as IPath,
      info: resp2.data as IPostNewInfo,
    };
  } catch (e) {
    return {
      isSuccess: false,
    };
  }
}

export default async function DashboardLayout({
  children,
  params: { locale },
}: {
  children: ReactNode;
  params: { locale: string };
}) {
  const data = await getData();

  if (data.isSuccess) {
    return (
      <Wrapper data={data.info!}>
        <EditNav locale={locale} />
        {children}
      </Wrapper>
    );
  }

  return <>{children}</>;
}
